<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/11/2 16:05
 */

namespace App\Http\Middleware;

use Closure;

class ExceptionConvertTo200Code
{
    /**
     * Handle an incoming request.
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if (200 !== $response->getStatusCode()) {
            return $this->{'exception' . $response->getStatusCode()}($response);
        }

        return $response;
    }

    public function exception422($response)
    {
        $errors = $response->exception->validator->errors();

        return response()->json([
            'data'    => $errors->keys(),
            'message' => $errors->first(),
            'code'    => '42200',
        ], 200);
    }

    public function exception404($response)
    {
        return response()->json([
            'message' => '未找到请求的资源。',
            'code'    => '40400',
        ], 200);
    }

    public function exception400($response)
    {
        return response()->json([
            'message' => $response->exception->getMessage(),
            'code'    => '40000',
        ], 200);
    }
    public function exception302($response)
    {
        return response()->json([
            'message' => $response->exception->getMessage(),
            'code'    => '40000',
        ], 200);
    }

    public function exception500($response)
    {
        dd($response->exception);

        $errors = $response->exception->validator->errors();


    }
}